package com.chj.comp.service.demo1.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.chj.comp.common.core.util.Result;
import com.chj.comp.service.demo1.dto.ExcelDescDTO;
import com.chj.comp.service.demo1.dto.ExcelSchedulerJobDownloadDTO;
import com.chj.comp.service.demo1.dto.ExcelSchedulerJobUploadDTO;
import com.chj.comp.service.demo1.listener.excel.ExcelUploadDataListener;
import com.chj.comp.service.demo1.service.IDemo1SchedulerJobService;
import com.chj.comp.service.demo1.service.IExcelTestService;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author ：cuihui
 * @date ：Created in 2022/4/17
 * @description：excel接口示例
 * @modified By：
 */
@Service
public class ExcelTestService implements IExcelTestService {

    @Autowired
    private IDemo1SchedulerJobService demo1SchedulerJobService;

    @Override
    public void downloadDemo(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 示例数据
        ExcelSchedulerJobDownloadDTO excelSchedulerJobDownloadDTO = new ExcelSchedulerJobDownloadDTO(
                "anjuke_job",
                "安居客数据爬虫定时任务",
                "*",
                "*",
                "*",
                "10",
                "22",
                "0",
                "0",
                null,
                "2",
                "邮件通知（新职位）",
                "2",
                "短信通知（新职位）"
        );
        // 说明描述
        ExcelDescDTO excelDescDTO = new ExcelDescDTO("请严格按照规范填写数据！\r\n"
                                                            +"模板提供者：cuihui\r\n"
                                                            +"如有问题，请联系：15502986569");

        // 单sheet
//        EasyExcel.write(response.getOutputStream(), ExcelSchedulerJobDownloadDTO.class)
//                .sheet("模板")
//                .doWrite(ListUtils.newArrayList(demo1SchedulerJobDTO));

        // 多sheet(不同对象)
        ExcelWriter excelWriter = null;
        try {
            // 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream()).build();

            // 模板sheet
            WriteSheet sheetData = EasyExcel.writerSheet("模板").head(ExcelSchedulerJobDownloadDTO.class).build();
            // 模板内容背景设置（DTO主要用于数据导出，模板样式在此处实现，参考：https://www.yuque.com/easyexcel/doc/write#W4u1e）
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 背景黄色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
            sheetData.setCustomWriteHandlerList(ListUtils.newArrayList(horizontalCellStyleStrategy));
            excelWriter.write(ListUtils.newArrayList(excelSchedulerJobDownloadDTO), sheetData);

            // 说明sheet（不要表格头）
            WriteSheet sheetDesc = EasyExcel.writerSheet("说明").head(ExcelDescDTO.class).build();
            sheetDesc.setNeedHead(Boolean.FALSE);
            excelWriter.write(ListUtils.newArrayList(excelDescDTO),
                              sheetDesc);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @Override
    public void downloadData(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("xxx数据", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 多sheet(同一对象)
        ExcelWriter excelWriter = null;
        try {
            // 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream(), ExcelSchedulerJobDownloadDTO.class).build();

            // 模板1
            WriteSheet sheet1Data = EasyExcel.writerSheet("数据1").build();
            excelWriter.write(demo1SchedulerJobService.list(), sheet1Data);

            // 模板2
            WriteSheet sheet2Data = EasyExcel.writerSheet("数据2").build();
            excelWriter.write(demo1SchedulerJobService.list(), sheet2Data);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @Override
    public Result uploadData(MultipartFile file) throws IOException {
        // 读取全部sheet
        // 这里需要注意 DemoDataListener的doAfterAllAnalysed 会在每个sheet读取完毕后调用一次。然后所有sheet都会往同一个DemoDataListener里面写
        EasyExcel.read(file.getInputStream(), ExcelSchedulerJobUploadDTO.class, new ExcelUploadDataListener(demo1SchedulerJobService))
                .doReadAll();
        return Result.ok("上传完成");
    }
}
